package com.flycent.hqhs.ui;

import java.lang.ref.WeakReference;
import java.util.List;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.annotation.view.ViewInject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.flycent.hqhs.App;
import com.flycent.hqhs.R;
import com.flycent.hqhs.bean.PageEntity;
import com.flycent.hqhs.bean.Product;
import com.flycent.hqhs.http.WebClient;
import com.flycent.hqhs.http.WebException;
import com.flycent.hqhs.ui.view.AbsViewHolderAdapter;
import com.flycent.hqhs.ui.view.CustomDigitalClock;
import com.flycent.hqhs.ui.view.RefreshViewLoadMoreProxy;
import com.flycent.hqhs.ui.view.RefreshViewLoadMoreProxy.OnLoadDataActionListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * @author fbl
 *  团购
 */
@SuppressLint("HandlerLeak") 
public class GroupActivity extends BackableTitleBarActivity implements OnLoadDataActionListener{
	@ViewInject(id = R.id.group_empty_relat ) RelativeLayout mEmptyRelat;

	PullToRefreshGridView mRefreshGridView;
	RefreshViewLoadMoreProxy mLoadMoreProxy;

	List<Product> mGroupProducts;
	private int nowpage = 1;
	private GroupListAdapter mAdapter;
	private static long nowDate;
	private MyHandler mHandler;

	//---------------------------------------------

	@Override
	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		setContentView(R.layout.activity_group);
		FinalActivity.initInjectedView(this);
		getTitleBar().setTitle(R.string.title_group);

		
		mHandler  = new MyHandler(this);

		mRefreshGridView = (PullToRefreshGridView) findViewById(R.id.group_list);

		mRefreshGridView.setEmptyView(mEmptyRelat);
		mRefreshGridView.getRefreshableView().setSelector(new ColorDrawable(Color.TRANSPARENT));

		mAdapter = new GroupListAdapter(GroupActivity.this, R.layout.item_group_grid_list);
		mRefreshGridView.setAdapter(mAdapter);

		mLoadMoreProxy = new RefreshViewLoadMoreProxy(mRefreshGridView, Mode.BOTH,0,0);
		mLoadMoreProxy.setOnLoadDataActionListener(this);
		mLoadMoreProxy.refreshing();
		mRefreshGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent,
					View view, int position, long id) {

				Intent intent = new Intent(GroupActivity.this,ProductDetailActivity.class);
				intent.putExtra("productID", mAdapter.getData().get(position).getId()+"");
				startActivity(intent);

			}

		});

	}

	@Override
	public void onRefresh(int page) {
		updateGroupList(1, true);
	}

	@Override
	public void onLoadMore(int page) {
		nowpage++;
		updateGroupList(nowpage, false);
	}

	private void updateGroupList(final int pageNum,final boolean isRefresh){
		//		mLoadMoreProxy.loadDataActionComplete(false);

		new Thread(){
			public void run() {
				WebClient client = WebClient.getInstance(GroupActivity.this);
				try {

					PageEntity<Product> entity = client.group(pageNum, 20, "endTime", "asc");

					int totlePage = entity.getTotalPages();
					nowDate = entity.getNowDate();
					mGroupProducts = entity.getContent();
					if(pageNum > totlePage){
						App.showShortToast(R.string.the_end_page);
						mGroupProducts = null;
					}
				} catch (WebException e) {
					if (WebException.TYPE_SERVER_RETURN_NULL.equals(e.getStatusCode())){
						mGroupProducts = null;
					}else
						e.printStackTrace();
				}

				if(isRefresh)
					mHandler.sendEmptyMessage(0);	
				else
					mHandler.sendEmptyMessage(1);
			};
		}.start();

		//		mLoadMoreProxy.loadDataActionComplete(true);
	}

	private class MyHandler extends Handler{

		private WeakReference<Activity> mActivity;

		private MyHandler(Activity activity){
			mActivity = new WeakReference<Activity>(activity);
		}
		@Override
		public void dispatchMessage(Message msg) {
			super.dispatchMessage(msg);
			if( mActivity.get() != null ){
				switch (msg.what) {
				case 0:
					mAdapter.update(mGroupProducts);
					mRefreshGridView.onRefreshComplete();
					break;
				case 1:
					mAdapter.append(mGroupProducts);
					mRefreshGridView.onRefreshComplete();
					break;
				default:
					break;
				}
			}

		}


	}


	public static class GroupListAdapter extends AbsViewHolderAdapter<Product>{

		public GroupListAdapter(Context context, int layoutRes) {
			super(context, layoutRes);
		}

		@Override
		protected void bindData(int pos, Product itemData) {

			ImageView mImageView = getViewFromHolder(R.id.item_group_image);
			TextView mNameTextView = getViewFromHolder(R.id.item_group_name_txt);
			TextView mPriceTextView = getViewFromHolder(R.id.item_group_price_txt);
			TextView mMarketPriceTextView = getViewFromHolder(R.id.item_group_market_price_txt);
			CustomDigitalClock remainTime = (CustomDigitalClock) getViewFromHolder(R.id.item_group_frame_text);
			TextView mPepoleNumberTextView = (TextView)getViewFromHolder(R.id.item_group_market_pepole_txt);
			mMarketPriceTextView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

			ImageLoader.getInstance().displayImage(itemData.getImage(),mImageView);
			mNameTextView.setText(itemData.getName());
			mPriceTextView.setText("￥"+itemData.getPrice());
			mMarketPriceTextView.setText("￥"+itemData.getReferencePrice());
			remainTime.setEndTime(System.currentTimeMillis()+(itemData.getEndTime()-nowDate));
			mPepoleNumberTextView.setText(itemData.getSales()+"");
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacksAndMessages(null);
	}


}
